<template>
	<el-dialog v-model="dialogFormVisible" title="添加宿管" width="500">
		<el-form :model="domi" label-width="100" :rules="rules" ref="ruleFormRef" status-icon>
			<el-form-item label="姓名">
				<el-input v-model="domi.houName" />
			</el-form-item>
			<el-form-item label="管理楼栋" prop="buildId">
				<el-input v-model.number="domi.buildId" />
			</el-form-item>
			<el-form-item label="职工号">
				<el-input v-model.number="domi.houId" />
			</el-form-item>
			<el-form-item label="电话">
				<el-input v-model.number="domi.phone" />
			</el-form-item>
			<el-form-item label="初始密码">
				<el-input v-model="domi.password" type="password" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAddDomi(ruleFormRef)"> 添加 </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { reactive, ref, getCurrentInstance } from 'vue'
import { addDomiAdminister } from '@/utils/axios/master'
import { getHouCount } from '@/utils/axios/getTotal'
import useRegStore from '@/stores/useReg'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const { phoneIsOk } = useRegStore()
const $emits = defineEmits(['get-total'])

const ruleFormRef = ref()

const domi = reactive({
	houName: '',
	buildId: '',
	houId: '',
	password: '',
	phone: '',
})

// 验证规则
const rules = reactive({
	buildId: [{ validator: checkBuild, trigger: 'blur' }],
})

const dialogFormVisible = defineModel('show')

// 添加宿管

const handleAddDomi = (formEl) => {
	if (!formEl) return
	formEl.validate(async (valid) => {
		if (valid) {
			if (!phoneIsOk(domi.phone)) return ElMessage.warning({ message: '手机号格式不正确', duration: 1000 })
			if (!domi.password) return ElMessage.warning({ message: '请设置初始密码', duration: 1000 })
			if (!domi.houName) return ElMessage.warning({ message: '请输入姓名', duration: 1000 })
			if (!domi.houId) return ElMessage.warning({ message: '请输入职工号', duration: 1000 })
			if (!domi.buildId) return ElMessage.warning({ message: '请输入管理楼栋', duration: 1000 })

			if (domi.password) {
				domi.password = proxy.$md5(domi.password)
			}
			domi.houId = Number.parseInt(domi.houId)
			domi.buildId = Number.parseInt(domi.buildId)
			await addDomiAdminister(domi)
			let { data } = await getHouCount()
			$emits('get-total', data)
			dialogFormVisible.value = false
			Object.assign(domi, { houName: '', buildId: '', houId: '', password: '', phone: '' })
		} else {
			console.log('error submit!')
		}
	})
}

function checkBuild(_, value, callback) {
	value = Number.parseInt(value)
	if (!value) return callback(new Error('请输入管理楼栋'))
	if (value < 0 || value > 20) return callback(new Error('楼栋必须为1-20栋'))
	callback()
}
</script>

<style scoped lang="scss"></style>
